package com.bjpowernode.interceptor;

import com.bjpowernode.beans.User;
import com.bjpowernode.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyLoginInterceptor implements HandlerInterceptor {


    @Autowired
    @Qualifier("userServicesFilter")
    UserServices userServices;


    //请求之前
    //返回 true：可以继续请求
    //返回 false：请求失败
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("拦截了【" + requestURI + "】页面");
        HttpSession session = request.getSession();
        User login = (User) session.getAttribute("user");
        if (login == null) {
            System.out.println("拦截器正在试图通过cookies登录（自定登录）");
            //获取cookies
            Cookie[] cookies = request.getCookies();
            String loginAct = "";
            String loginPwd = "";

            if(cookies==null){
                response.sendRedirect("/static/login.html");
                return false;
            }


            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("loginAct")) {
                    loginAct = cookie.getValue();
                }
                if (cookie.getName().equals("loginPwd")) {
                    loginPwd = cookie.getValue();
                }
            }
            User loginTemp = userServices.login(loginAct, loginPwd);
            if(loginTemp==null){
                response.sendRedirect("/static/login.html");
                return false;
            }
            else{
                //自动登录成功放到session
                session.setAttribute("user",loginTemp);
                //放行
                return true;
            }

        } else {
            return true;
        }
    }

    //响应之后，但是没有到界面【或者浏览器】
    //响应之后，【视图解析器解析之前】
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //响应结束了
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
